package com.wyp168.renrenfilm.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wyp168.renrenfilm.core.dto.UserDTO;
import com.wyp168.renrenfilm.core.feign.RenrenFastFeign;
import com.wyp168.renrenfilm.core.service.RequireService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class RequireServiceImpl implements RequireService {

    @Autowired
    private RenrenFastFeign renrenFastFeign;

    @Override
    public String getLoginUser(String token) {
        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("token为空");
        }

        JSONObject info = renrenFastFeign.info(token);


        JSONObject user = info.getJSONObject("user");

        return user.getString("username");
    }

    @Override
    public String getLoginUserByRequest(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("token为空");
        }

        JSONObject info = renrenFastFeign.info(token);


        JSONObject user = info.getJSONObject("user");

        return user.getString("username");
    }

    @Override
    public UserDTO getLoginUserObjByToken(String token) {
        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("getLoginUserObjByToken， token为空");
        }

        JSONObject info = renrenFastFeign.info(token);
        if (info.getInteger("code") == 401) {
            throw new RuntimeException("token失效，请重新登录");
        }
        JSONObject userJsonObj = info.getJSONObject("user");

        UserDTO user = userJsonObj.toJavaObject(UserDTO.class);
        return user;
    }

}
